﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime;
using System.Windows;
using Caliburn.Micro;
using GTServices.WPF.Client;
using GTServices.WPF.Client.ViewModels;
using GTServices.Entities;
using GTServices.Model;
using GTServices.Model.Models;
using GTServices.Model.CoRoutine;
using GTServices.WPF.Client.ViewModels.Entities;
using GTServices.WPF.Client.CoRoutines;


namespace GTServices.WPF.Client.ViewModels
{
    public class RootViewModel : Screen
    {
        
        public object _activeViewModel;
        public object ActiveViewModel {
            get { return _activeViewModel; }
            set
            {
                _activeViewModel = value;
                NotifyOfPropertyChange(() => ActiveViewModel);
            }
        }

        public SelectItemsViewModel  SelectCategoriesViewModel { get; set; }
        public GrepResultsTreeViewModel SearchResultsTreeView { get; set; }
        public ManageViewModel ManageViewModel { get; set; }
        public String Status { get; set; }
        public String Path { get; set; }

        public bool IsRunning { get; set; }

        public RootViewModel()
        {
            try
            {
                GTApplication app = GTApplication.Instance;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            //Add the main control panel. 
            this.SelectCategoriesViewModel = new SelectItemsViewModel();
            this.SearchResultsTreeView = new GrepResultsTreeViewModel();
            this.ManageViewModel = new ManageViewModel(); 
            this.Status = "Ready..";
        }


        public void SelectCategories(){
            SelectItemsViewModel sivm = new SelectItemsViewModel();
            GTWindowManager.Instance.ShowWindow(sivm, 300, 300); 
           // winMgr.ShowWindow(sivm); 
        }
        public void Manage()
        {
            GTWindowManager.Instance.ShowDialog(this.ManageViewModel, 554, 1006);
        }

        public void Search()
        {   
            
            var searchDialog = new GTSearchDialogViewModel() { Path = this.Path };
            GTWindowManager.Instance.ShowWindow(searchDialog, 500, 300);
        }
   
        public void SaveAll()
        {
            try
            {
                GTApplication.Instance.DataModel.SaveState();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
      

        public void PickDir()
        {
            
            System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();

            if (System.IO.Directory.Exists(this.Path))
                fbd.SelectedPath = this.Path;

            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.Path = fbd.SelectedPath;
                NotifyOfPropertyChange(() => Path);
            }
        }
        public void PickSln()
        {
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();

            ofd.Filter = "Solution Files (*.sln)|*.sln| Project Files (*.*proj)| *.*proj";
            ofd.FilterIndex = 0;
            if (ofd.ShowDialog() == true)
            {
                this.Path = ofd.FileName;
                NotifyOfPropertyChange(() => Path);
            }
        }

        public void Start()
        {
            if (IsRunning)
            {
                MessageBox.Show("Already running");
                return;
            }
            IsRunning = true;

            this.Status = "Running..";
            NotifyOfPropertyChange(() => Status);
            var categories = ModelViewModels.Instance.CategoryViewModels.Where( x=> x.IsSelected).Select( x=>x.Category).ToList();
            var patterns = ModelViewModels.Instance.PatternViewModels.Where( x=> x.IsSelected).Select( x=> x.Pattern).ToList();
            var languages = ModelViewModels.Instance.LanguageViewModels.Where(x => x.IsSelected).Select(x => x.Language).ToList(); 
            if (patterns.Count() == 0)
            {
                IsRunning = false;
                MessageBox.Show("No patterns selected");
                this.Status = "Errored..";
                NotifyOfPropertyChange(() => Status);

                return; 
            }
            try
            {
                GrepRequest gr = GTApplication.Instance.GrepModel.GetGrepRequest(Path, patterns, languages, categories, null);

                
                ExecuteDirectoryGrepRequestRoutine routine = new ExecuteDirectoryGrepRequestRoutine(gr);
                routine.OnNextDirectory += new ExecuteDirectoryGrepRequestRoutine.NextDirectory((x, y) =>
                {
                    this.Status = x;
                    NotifyOfPropertyChange(() => Status);
                });
                /*
                 ExecuteGrepRequestRoutine routine = new ExecuteGrepRequestRoutine(gr);
                  */
                routine.Completed += (x, y) =>
                {
                    if(y.Error == null){
                        GTApplication.Instance.DataModel.GrepResults.Add(routine.Result);
                        this.Status = "Completed";
                    }
                    else
                    {
                        this.Status = "Errored.." + y.Error.Message;
                    }
                    NotifyOfPropertyChange(() => Status);
                    IsRunning = false;
                };

              

                //StatusWindowViewModel statusWin = new StatusWindowViewModel(routine);
                //GTWindowManager.Instance.ShowWindow(statusWin, 100, 300); 

                Dispatcher.Instance.QueueItem(routine); 
            }
            catch (Exception e)
            {     
                this.Status = "Errored..";
                IsRunning = false;
                NotifyOfPropertyChange(() => Status);
                MessageBox.Show(e.Message);
               
            }

          
        }
        public void ImportPatternsFromTxt()
        {

            var languages = ModelViewModels.Instance.LanguageViewModels.ToList();

            ListPickerViewModel lpvm = new ListPickerViewModel(languages.ToList<Object>(), "Language.Name", "Language.Name");

            
            if (GTWindowManager.Instance.ShowDialog(lpvm,300,300) == true && lpvm.SelectedItem != null)
            {
                Language language = (lpvm.SelectedItem as LanguageViewModel).Language;
                 Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();

                if (ofd.ShowDialog() == true)
                {
                    string file = ofd.FileName;
                    GTApplication.Instance.DataModel.LoadPatternsFromFile(file, language);
                }
            }
        }

        public void ShowOptions()
        {
            OptionsViewModel ovm = new OptionsViewModel();

            GTWindowManager.Instance.ShowDialog(ovm, 400, 300); 

        }
        public void Exit()
        {
            Application.Current.Shutdown(); 
        }
        public void ShowDirectoryFilters()
        {
            GTWindowManager.Instance.ShowDialog(new DirectoryFilterViewModel(), 300, 300);
        }
        public void ImportEntityXml()
        {

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".xml"; // Default file extension
            dlg.Filter = "Xml Documents (.xml)|*.xml"; // Filter files by extension 
            dlg.Multiselect = true;

            if (dlg.ShowDialog() == true)
            {

                ImportCommand ic = new ImportCommand(dlg.FileNames.ToList());

                ic.Completed += (x, y) =>
                {
                    if (ic.Success == true)
                    {
                        MessageBox.Show("Import successful");
                    }
                    else
                    {
                        MessageBox.Show("Import Failed");
                    }
                };

                StatusWindowViewModel statusWindow = new StatusWindowViewModel(ic, "Importing, Please Wait..");

                GTWindowManager.Instance.ShowWindow(statusWindow, 100, 300);

                Dispatcher.Instance.QueueItem(ic);
            }
     
        
        }
    }
}
